package com.kele.controller;

import com.kele.entity.Student;
import com.kele.entity.User;
import com.kele.service.impl.StudentServiceImpl;
import com.kele.utils.R;
import com.kele.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author kele
 * @date 2021/8/12 11:53
 * @description
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentServiceImpl studentService;

    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/findAll")
    public R findAll(){

        if (redisUtil.get("studentAll")==null){
            List<Student> studentList = studentService.findAll();

            if (studentList.size()!=0){
                return R.ok(200,"查找全部用户信息成功").put("data",studentList);
            }
        }else {
            List<Student> studentAll = (List<Student>) redisUtil.get("studentAll");
            if (studentAll!=null){
                return R.ok(200,"查找全部用户信息").put("data",studentAll);
            }
        }
        return R.error(404,"没有找到用户信息");

    }

    @GetMapping("/findById/{id}")
    public R findById(@PathVariable("id") Integer id){

        if(redisUtil.get("student" + id)==null){
            Student student = studentService.findStudentById(id);
            if (student!=null){
                return R.ok(200,"通过ida查找用户信息").put("data",student);
            }
        }else {
           Student student= (Student) redisUtil.get("student" + id);
            if (student!=null){
                return R.ok(200,"通过ida查找用户信息").put("data",student);
            }
        }
        return R.error(404,"没有找到用户信息");

    }
    @PutMapping("/update/{id}")
    public R updateStudent(@PathVariable("id") Integer id){

        Student student = studentService.findStudentById(id);
        student.setName("kele");
        student.setSex("men");

        int i = studentService.updateStudent(student);
        if (i>0){
            return R.ok(200,"修改成功");
        }
        return R.error(200,"修改失败");
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Integer id){

        int i = studentService.deleteStudent(id);
        if (i>0){
            return R.ok(200,"删除成功");
        }

        return R.error(200,"删除失败");
    }

    @PostMapping("/insert")
    public R insertUser(@RequestBody Student student){
//        Student student=new Student();
//        Date date=new Date();
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        String format1 = format.format(date);
//        student.setName("demo");
//        student.setSex("menAndwomen");
//        student.setBirth(format1);
        int i = studentService.insertStudent(student);
        if(i>0){
            return R.ok(200,"新增成功");
        }
        return R.error(200,"新增失败");
    }
}
